/*
 * 10.4.cpp 1661_poj
 *
 *  Created on: 2012-5-24
 *      Author: ncrd
 */


#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <cstring>

using namespace std;

#define N 1010
#define INFINITE 1000000

struct PLATFORM {
	int left, right, height;
};

PLATFORM platform[N];
int minLeft[N], minRight[N];
int num, maxSpeed;;

int compare(const void * a, const void *b) {
	return ((PLATFORM *)b)->height - ((PLATFORM *)a)->height;
}

int main (void) {
	int n;
	scanf("%d", &n);
	while (n--) {
		scanf("%d%d%d%d", &num, &platform[0].left, &platform[0].height, &maxSpeed);
		platform[0].right = platform[0].left;
		memset(minLeft, -1, sizeof(minLeft));
		memset(minRight, -1, sizeof(minRight));
		for (int i=1; i<=num; i++) {
			scanf("%d %d %d", &platform[i].left, &platform[i].right, &platform[i].height);
		}
		qsort(platform, num+1, sizeof(PLATFORM), compare);
		minLeft[num+1] = minRight[num+1] = 0;
		platform[num+1].height = 0;
		platform[num+1].left = -20001;
		platform[num+1].right = 20001;
		for (int i=num; i>=0; i--) {
			int x, *min;
			for (int tmp = 0; tmp < 2; tmp++) {
				int j, h;
				if (tmp == 0) {
					x = platform[i].left;
					min = &minLeft[i];
				} else {
					x = platform[i].right;
					min = &minRight[i];
				}
				for (j=i+1; j<=num+1; j++) {
					if (x >= platform[j].left && x <= platform[j].right) break;
				}
				h = platform[i].height - platform[j].height;
				if(h > maxSpeed) {
					*min = INFINITE;
					continue;
				} else if(j>num){
					*min = h;
					continue;
				}
				int leftTime = x - platform[j].left + minLeft[j];
				int rightTime = platform[j].right - x + minRight[j];
				int minTime = h + leftTime;
				if(rightTime < minTime) minTime = h + rightTime;
				*min = minTime;
			}
		}
		printf("%d\n", minLeft[0]);
	}
	return 0;
}
